package dj.common.lang.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.*;
import java.util.regex.Pattern;

public class Security {

    private static Log logger = LogFactory.getLog(Security.class);

    private static Pattern p = Pattern
        .compile("^((13[0-9])|(16[0-9])|(17[0-9])|(15[0-9])|(18[0-9])|(19[0-9])|(14[0-9]))\\d{8}$");

    /**
     * 获取单个文件的MD5值！
     *
     * @param file
     *
     * @return
     */
    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[4096];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            logger.error("ERROR:", e);
            return null;
        }
        // BigInteger bigInt = new BigInteger(1, digest.digest());
        // return bigInt.toString(16);
        byte[] result = digest.digest();
        StringBuilder sb = new StringBuilder();
        for (byte t : result) {
            String s = Integer.toHexString(t & 0xFF);
            if (s.length() == 1)
                s = "0" + s;
            sb.append(s);
        }
        return sb.toString();
    }

    public static String fileToMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        return null;
    }

    public static byte[] aesDecryptToBytes(String content, String decryptKey) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(decryptKey.getBytes()));

            // Cipher cipher = Cipher.getInstance("AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            IvParameterSpec iv = new IvParameterSpec(
                "0102030405060708".getBytes());
            SecretKeySpec secretKeySpec = new SecretKeySpec(kgen.generateKey()
                .getEncoded(), "AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv);
            return cipher.doFinal(content.getBytes("utf-8"));
        } catch (Exception e) {
            logger.error("ERROR:", e);
            return null;
        }
    }

    public static String aesDecrypt(String content, String decryptKey) {
        try {
            return new String(aesDecryptToBytes(content, decryptKey), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("ERROR:", e);
            return null;
        }
    }

    public static byte[] aesEncryptToBytes(String content, String encryptKey) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(encryptKey.getBytes()));

            // Cipher cipher = Cipher.getInstance("AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            IvParameterSpec iv = new IvParameterSpec(
                "0102030405060708".getBytes());
            byte[] encoded = kgen.generateKey().getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(encoded, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv);
            return cipher.doFinal(content.getBytes("utf-8"));
        } catch (Exception e) {
            logger.error("ERROR:", e);
            return null;
        }
    }

    public static String aesEncryptToHexString(String content, String encryptKey) {
        return toHexString(aesEncryptToBytes(content, encryptKey));
    }

    public static String aesEncryptToBase64(String content, String encryptKey) {
        return Base64
            .encodeBase64String(aesEncryptToBytes(content, encryptKey));
    }

    /**
     * 进行MD5加密
     *
     * @param info 要加密的信息
     *
     * @return String 加密后的字符串
     */
    public static String encryptToMD5(String info) {
        byte[] digesta = null;
        try {
            // 得到一个md5的消息摘要
            MessageDigest alga = MessageDigest.getInstance("MD5");
            // 添加要进行计算摘要的信息
            alga.update(info.getBytes());
            // 得到该摘要
            digesta = alga.digest();
        } catch (NoSuchAlgorithmException e) {
            logger.error("ERROR:", e);
        }
        // 将摘要转为字符串
        String rs = byte2hex(digesta);
        return rs;
    }

    public static String encryptToSHA256(String info) {
        byte[] digesta = null;
        try {
            // 得到一个SHA-1的消息摘要
            MessageDigest alga = MessageDigest.getInstance("SHA-256");
            // 添加要进行计算摘要的信息
            alga.update(info.getBytes());
            // 得到该摘要
            digesta = alga.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if (digesta != null) {
            // 将摘要转为字符串
            String rs = byte2hex(digesta);
            return rs;
        }
        return "";
    }

    /**
     * 进行SHA加密
     *
     * @param info 要加密的信息
     *
     * @return String 加密后的字符串
     */
    public static String encryptToSHA(String info) {
        byte[] digesta = null;
        try {
            // 得到一个SHA-1的消息摘要
            MessageDigest alga = MessageDigest.getInstance("SHA-1");
            // 添加要进行计算摘要的信息
            alga.update(info.getBytes());
            // 得到该摘要
            digesta = alga.digest();
        } catch (NoSuchAlgorithmException e) {
            logger.error("ERROR:", e);
        }
        // 将摘要转为字符串
        String rs = byte2hex(digesta);
        return rs;
    }

    // //////////////////////////////////////////////////////////////////////////

    /**
     * 创建密匙
     *
     * @param algorithm 加密算法,可用 DES,DESede,Blowfish
     *
     * @return SecretKey 秘密（对称）密钥
     */
    public SecretKey createSecretKey(String algorithm) {
        // 声明KeyGenerator对象
        KeyGenerator keygen;
        // 声明 密钥对象
        SecretKey deskey = null;
        try {
            // 返回生成指定算法的秘密密钥的 KeyGenerator 对象
            keygen = KeyGenerator.getInstance(algorithm);
            // 生成一个密钥
            deskey = keygen.generateKey();
        } catch (NoSuchAlgorithmException e) {
            logger.error("ERROR:", e);
        }
        // 返回密匙
        return deskey;
    }

    public static String encrypt(String message, String key) {
        try {
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

            DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));

            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
            IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
            return toHexString(cipher.doFinal(message.getBytes("UTF-8")));
        } catch (Exception e) {
            logger.error("ERROR:", e);
            return null;
        }
    }

    public static String desDecrypt(String message, String key) {
        try {
            byte[] bytesrc = convertHexString(message);
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
            IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));

            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

            byte[] retByte = cipher.doFinal(bytesrc);
            return new String(retByte, "UTF-8");
        } catch (Exception e) {
            logger.error("ERROR:", e);
            return null;
        }
    }

    public static String decrypt(String message, String key, String algorithm) {
        if ("des".equalsIgnoreCase(algorithm)) {
            return desDecrypt(message, key);
        } else if ("aes".equalsIgnoreCase(algorithm)) {
            return aesDecrypt(message, key);
        } else {
            return null;
        }
    }

    public static String decrypt(String message, String key) {
        return desDecrypt(message, key);
    }

    public static String DesBase64(String message, String key) {
        try {
            byte[] bytesrc = Base64.decodeBase64(message);
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
            // IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] retByte = cipher.doFinal(bytesrc);
            return new String(retByte, "UTF-8");
        } catch (Exception e) {
            logger.error("ERROR:", e);
            return null;
        }

    }

    public static byte[] convertHexString(String ss) {
        byte digest[] = new byte[ss.length() / 2];
        for (int i = 0; i < digest.length; i++) {
            String byteString = ss.substring(2 * i, 2 * i + 2);
            int byteValue = Integer.parseInt(byteString, 16);
            digest[i] = (byte) byteValue;
        }

        return digest;
    }

    public static String toHexString(byte b[]) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String plainText = Integer.toHexString(0xff & b[i]);
            if (plainText.length() < 2)
                plainText = "0" + plainText;
            hexString.append(plainText);
        }

        return hexString.toString();
    }

    // /////////////////////////////////////////////////////////////////////////////

    /**
     * 创建密匙组，并将公匙，私匙放入到指定文件中
     * <p>
     * 默认放入mykeys.bat文件中
     */
    public void createPairKey() {
        try {
            // 根据特定的算法一个密钥对生成器
            KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
            // 加密随机数生成器 (RNG)
            SecureRandom random = new SecureRandom();
            // 重新设置此随机对象的种子
            random.setSeed(1000);
            // 使用给定的随机源（和默认的参数集合）初始化确定密钥大小的密钥对生成器
            keygen.initialize(512, random);// keygen.initialize(512);
            // 生成密钥组
            KeyPair keys = keygen.generateKeyPair();
            // 得到公匙
            PublicKey pubkey = keys.getPublic();
            // 得到私匙
            PrivateKey prikey = keys.getPrivate();
            // 将公匙私匙写入到文件当中
            doObjToFile("mykeys.bat", new Object[]{prikey, pubkey});
        } catch (NoSuchAlgorithmException e) {
            logger.error("ERROR:", e);
        }
    }

    /**
     * 利用私匙对信息进行签名 把签名后的信息放入到指定的文件中
     *
     * @param info     要签名的信息
     * @param signfile 存入的文件
     */
    public void signToInfo(String info, String signfile) {
        // 从文件当中读取私匙
        PrivateKey myprikey = (PrivateKey) getObjFromFile("mykeys.bat", 1);
        // 从文件中读取公匙
        PublicKey mypubkey = (PublicKey) getObjFromFile("mykeys.bat", 2);
        try {
            // Signature 对象可用来生成和验证数字签名
            Signature signet = Signature.getInstance("DSA");
            // 初始化签署签名的私钥
            signet.initSign(myprikey);
            // 更新要由字节签名或验证的数据
            signet.update(info.getBytes());
            // 签署或验证所有更新字节的签名，返回签名
            byte[] signed = signet.sign();
            // 将数字签名,公匙,信息放入文件中
            doObjToFile(signfile, new Object[]{signed, mypubkey, info});
        } catch (Exception e) {
            logger.error("ERROR:", e);
        }
    }

    /**
     * 读取数字签名文件 根据公匙，签名，信息验证信息的合法性
     *
     * @return true 验证成功 false 验证失败
     */
    public boolean validateSign(String signfile) {
        // 读取公匙
        PublicKey mypubkey = (PublicKey) getObjFromFile(signfile, 2);
        // 读取签名
        byte[] signed = (byte[]) getObjFromFile(signfile, 1);
        // 读取信息
        String info = (String) getObjFromFile(signfile, 3);
        try {
            // 初始一个Signature对象,并用公钥和签名进行验证
            Signature signetcheck = Signature.getInstance("DSA");
            // 初始化验证签名的公钥
            signetcheck.initVerify(mypubkey);
            // 使用指定的 byte 数组更新要签名或验证的数据
            signetcheck.update(info.getBytes());
            // 验证传入的签名
            return signetcheck.verify(signed);
        } catch (Exception e) {
            logger.error("ERROR:", e);
            return false;
        }
    }

    /**
     * 将二进制转化为16进制字符串
     *
     * @param b 二进制字节数组
     *
     * @return String
     */
    public static String byte2hex(byte[] b) {
        // String hs = "";
        StringBuffer stmp = new StringBuffer();
        for (int n = 0; n < b.length; n++) {
            String hex = (Integer.toHexString(b[n] & 0XFF));
            if (hex.length() == 1) {
                // hs = hs + "0" + stmp;
                stmp.append("0").append(hex);
            } else {
                // hs = hs + stmp;
                stmp.append(hex);
            }
        }
        return stmp.toString().toUpperCase();
    }

    /**
     * 十六进制字符串转化为2进制
     *
     * @param hex
     *
     * @return
     */
    public static byte[] hex2byte(String hex) {
        byte[] ret = new byte[8];
        byte[] tmp = hex.getBytes();
        for (int i = 0; i < 8; i++) {
            ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
        }
        return ret;
    }

    /**
     * 将两个ASCII字符合成一个字节； 如："EF"--> 0xEF
     *
     * @param src0 byte
     * @param src1 byte
     *
     * @return byte
     */
    public static byte uniteBytes(byte src0, byte src1) {
        byte _b0 = Byte.decode("0x" + new String(new byte[]{src0}))
            .byteValue();
        _b0 = (byte) (_b0 << 4);
        byte _b1 = Byte.decode("0x" + new String(new byte[]{src1}))
            .byteValue();
        byte ret = (byte) (_b0 ^ _b1);
        return ret;
    }

    /**
     * 将指定的对象写入指定的文件
     *
     * @param file 指定写入的文件
     * @param objs 要写入的对象
     */
    public void doObjToFile(String file, Object[] objs) {
        ObjectOutputStream oos = null;
        try {
            FileOutputStream fos = new FileOutputStream(file);
            oos = new ObjectOutputStream(fos);
            for (int i = 0; i < objs.length; i++) {
                oos.writeObject(objs[i]);
            }
        } catch (Exception e) {
            logger.error("ERROR:", e);
        } finally {
            try {
                oos.close();
            } catch (IOException e) {
                logger.error("ERROR:", e);
            }
        }
    }

    /**
     * 返回在文件中指定位置的对象
     *
     * @param file 指定的文件
     * @param i    从1开始
     *
     * @return
     */
    public Object getObjFromFile(String file, int i) {
        ObjectInputStream ois = null;
        Object obj = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ois = new ObjectInputStream(fis);
            for (int j = 0; j < i; j++) {
                obj = ois.readObject();
            }
        } catch (Exception e) {
            logger.error("ERROR:", e);
        } finally {
            try {
                ois.close();
            } catch (IOException e) {
                logger.error("ERROR:", e);
            }
        }
        return obj;
    }

    public static boolean isValidMobile(long mob) {
        return isValidMobile(String.valueOf(mob));
    }

    public static boolean isValidMobile(String mob) {
//        Matcher m = p.matcher(mob);
//        return m.matches();
        return true;
    }


    public static void main(String[] args) {
        String mobcb123 = Security.encrypt("123123", "MOBCB123");
        // log.debug(mobcb123);
        // log.debug(Security.decrypt(mobcb123,"MOBCB123"));
    }
}
